package fr.umlv.m2.jee.spij.web.file.display;

import fr.umlv.m2.jee.spij.persistence.education.Lesson;
import fr.umlv.m2.jee.spij.persistence.education.dao.HibernateLessonDAO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.OutputStream;

/**
 *
 */
@Component("mediaBean")
public class MediaBean {

    /**
     * DAO.
     */
    @Autowired
    private HibernateLessonDAO lessonDAO;

    /**
     * Logger.
     */
    private final Log log = LogFactory.getLog(MediaBean.class);

    private static final String TEMPORARY_PDF_NAME = "/pdf/content.pdf";

    /**
     * Empty constructor
     */
    public MediaBean() {
    }

    @Transactional(readOnly = true)
    public void paint(OutputStream stream, Object id) throws IOException {
        log.error("IN : Class MediaBean - Method paint");

        final Lesson lesson = lessonDAO.findById((Long) id);
        if (lesson != null) {
            final byte[] data = lesson.getFileData();
            if (data != null) {
                stream.write(data);
                stream.flush();
                // stream.close();
                log.error("stream succeed");
            } else {
                log.error("Content lesson is empty");
            }
        } else {
            log.error("Lesson is null");
        }

        log.error("OUT");
    }

    /**
     * get the current date
     *
     * @return a timestamp of the current date
     */
    public long getTimeStamp() {
        log.info("media time stamp");
        return System.currentTimeMillis();
    }
}
